const { SerialPort } = require('serialport');

// 获取所有可用串口列表
async function listSerialPorts() {
    try {
        const ports = await SerialPort.list();
        console.log('可用串口列表：');
        ports.forEach(port => {
            console.log(`${port.path} - ${port.manufacturer || '未知制造商'}`);
        });
        return ports;
    } catch (err) {
        console.error('获取串口列表失败:', err);
        throw err;
    }
}

// 连接串口
function connectSerialPort(portPath, options = {}) {
    const defaultOptions = {
        baudRate: 9600,
        dataBits: 8,
        stopBits: 1,
        parity: 'none',
        autoReconnect: true,     // 自动重连选项
        reconnectInterval: 5000  // 重连间隔（毫秒）
    };

    const finalOptions = { ...defaultOptions, ...options };
    let port = null;
    let reconnectTimer = null;

    function connect() {
        try {
            port = new SerialPort({
                path: portPath,
                ...finalOptions
            });

            port.on('open', () => {
                console.log(`串口 ${portPath} 已成功打开`);
                if (reconnectTimer) {
                    clearInterval(reconnectTimer);
                    reconnectTimer = null;
                }
            });

            port.on('data', (data) => {
                console.log('收到数据:', data.toString('hex'));
            });

            port.on('error', (err) => {
                console.error('串口错误:', err);
                if (finalOptions.autoReconnect && !reconnectTimer) {
                    reconnectTimer = setInterval(() => {
                        console.log('尝试重新连接...');
                        connect();
                    }, finalOptions.reconnectInterval);
                }
            });

            port.on('close', () => {
                console.log('串口已关闭');
                if (finalOptions.autoReconnect && !reconnectTimer) {
                    reconnectTimer = setInterval(() => {
                        console.log('尝试重新连接...');
                        connect();
                    }, finalOptions.reconnectInterval);
                }
            });
        } catch (err) {
            console.error('连接串口失败:', err);
            throw err;
        }
    }

    connect();
    return port;
}

// 发送数据到串口
function sendToPort(port, data) {
    return new Promise((resolve, reject) => {
        if (!port || !port.isOpen) {
            reject(new Error('串口未打开'));
            return;
        }

        port.write(data, (err) => {
            if (err) {
                console.error('发送数据失败:', err);
                reject(err);
                return;
            }
            console.log('数据发送成功:', data);
            resolve(true);
        });
    });
}

const sendData = {}

if(typeof sendData === 'object'){
    console.log('sendData是一个对象');
}else{
    console.log('sendData不是一个对象');
}
